package project.ia04.agents.studio.StaffAgentCommunication;

import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import project.ia04.agents.studio.StudioAgent;
import project.ia04.utils.Data;

public class SendActionMessageBehaviour extends OneShotBehaviour {

	private ACLMessage message;
	
	public SendActionMessageBehaviour(ACLMessage message){
		this.message = message;
	}
	
	@Override
	public void action() {
		ACLMessage newMess = new ACLMessage(ACLMessage.INFORM);
		newMess.setConversationId(Data.STAFFACTION);
		newMess.addReceiver(((StudioAgent)myAgent).getXAgent());
		newMess.setContent(serialize());
		myAgent.send(newMess);
	}

	private String serialize() {
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put(Data.STAFFNAME, message.getSender().getLocalName());
		map.put(Data.STAFFMSG,message.getContent());
		StringWriter sw = new StringWriter();
		try {
			mapper.writeValue(sw, map);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sw.toString();
	}

}
